from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QMessageBox
from ui.MainWindow import Ui_MainWindow
from image_window import MyImageWindow
from PIL import Image, UnidentifiedImageError
from canvas_window import MyCanvasWindow
import sys


class MyMainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        # setup main window
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setFixedSize(550, 394)

        # instance of image window
        self.img_window = None
        self.canvas_window = None
        # set up signals and slots
        self.init_actions()

        # change font size on Windows:
        if sys.platform == 'win32':
            self.ui.label.setFont(QFont("Roman times", 18, QFont.Bold))

    def init_actions(self):  # connect signals and slots
        """
        连接信号槽，也就是事件发生时要触发的函数
        """
        self.ui.actionOpen.triggered.connect(self.open_file)
        self.ui.open_file_Button.clicked.connect(self.open_file)
        self.ui.new_file_Button.clicked.connect(self.draw_new_image)
        self.ui.actionNew.triggered.connect(self.draw_new_image)
        self.ui.actionExit.triggered.connect(lambda: sys.exit())

    def open_file(self):
        filename, _ = QFileDialog.getOpenFileName(self, 'Choose an image', './', 'Images (*.jpg *.png *.tif *.bmp)')

        # 尝试打开图片，如果失败弹出提示窗口
        if filename:
            try:
                img = Image.open(filename)
            except UnidentifiedImageError or AttributeError:
                msg = QMessageBox()
                msg.setWindowTitle('Error')
                msg.setText("File can't be opened!")
                msg.setIcon(QMessageBox.Critical)
                _ = msg.exec_()
                return

            if not (img.mode == '1' or 'L' or 'RGB'):
                msg = QMessageBox()
                msg.setWindowTitle('Error')
                msg.setText("File can't be opened!")
                msg.setIcon(QMessageBox.Critical)
                _ = msg.exec_()
                return

            self.img_window = MyImageWindow(filename, img.width, img.height)
            self.img_window.show()  # show img_window
            self.hide()  # hide current window
            self.img_window.closed.connect(lambda: self.show())  # show current window when img_window is closed

    def draw_new_image(self):
        self.canvas_window = MyCanvasWindow()
        self.canvas_window.show()
        self.hide()  # hide current window
        self.canvas_window.closed_.connect(lambda: self.show())


if __name__ == '__main__':
    """
    程序入口，新建一个主窗口并打开
    """
    app = QApplication(sys.argv)
    win = MyMainWindow()
    #窗口背景图片
    win.setStyleSheet("#MainWindow{border-image:url(./ui/1.jpg);}")
    win.show()
    sys.exit(app.exec_())
